package me.helllp.dake.iam.core.dao.impl;

import me.helllp.dake.common.exception.DakeEncryptException;
import me.helllp.dake.common.security.CryptoUtil;
import me.helllp.dake.core.IdGenerator;
import me.helllp.dake.core.bean.DakeAuthAccount;
import me.helllp.dake.core.crypto.SecuritySerivce;
import me.helllp.dake.core.utils.PoUtil;
import me.helllp.dake.iam.core.bo.AccountBo;
import me.helllp.dake.iam.core.convert.AccountConvert;
import me.helllp.dake.iam.core.po.DakeAccount;
import me.helllp.dake.iam.core.mapper.DakeAccountMapper;
import me.helllp.dake.iam.core.dao.IDakeAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dake
 * @since 2022-12-05
 */
@Service
public class DakeAccountServiceImpl extends ServiceImpl<DakeAccountMapper, DakeAccount> implements IDakeAccountService {

    @Autowired
    private AccountConvert accountConvert;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private SecuritySerivce securitySerivce;

    @Override
    public Long creatAccount(AccountBo bo, DakeAuthAccount user) throws UnsupportedEncodingException, DakeEncryptException {
        DakeAccount account = this.accountConvert.toAccount(bo);
        account.setId(this.idGenerator.nextId());

        if (!StringUtils.isEmpty(account.getPassword())) {
            account.setSalt(CryptoUtil.genSalt(128));
            String pass = account.getPassword() + account.getSalt();
            account.setPassword(this.securitySerivce.sha1ToHex(pass));
        }

        PoUtil.setInsertPo(account, user.getUserAccount());
        return save(account) ? account.getId() : null;
    }

    @Override
    public Boolean modifyAccount(AccountBo bo, DakeAuthAccount user) {
        DakeAccount account = this.accountConvert.toAccount(bo);
        PoUtil.setUpdatePo(account, user.getUserAccount());
        return Boolean.valueOf(saveOrUpdate(account));
    }

    @Override
    public Boolean deleteAccount(Long accountId) {
        return Boolean.valueOf(removeById(accountId));
    }

    @Override
    public Boolean checkPassword(DakeAccount account, String password)  {
        String pass = password + account.getSalt();
        return Boolean.valueOf(account.getPassword().equals(this.securitySerivce.sha1ToHex(pass)));
    }
}
